package com.android.webttest.ViewModel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.android.webttest.Api.Service.AppApiService;
import com.android.webttest.Api.Service.CheckcodeApiService;
import com.android.webttest.Api.Service.UserApiService;
import com.android.webttest.Config.ApiClient;
import com.android.webttest.model.Result;
import com.android.webttest.model.User;
import com.android.webttest.utils.TokenManager;

import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainViewModel extends AndroidViewModel {

    private MutableLiveData<Bitmap> captchaImage;
    private MutableLiveData<String> authToken;
    private MutableLiveData<String> toastMessage;

    private MutableLiveData<User> userInfo;

    private CheckcodeApiService checkcodeApiServiceService;
    private UserApiService userApiService;

    private AppApiService appApiService;
    public MainViewModel(@NonNull Application application) {
        super(application);
        captchaImage = new MutableLiveData<>();
        authToken = new MutableLiveData<>();
        toastMessage = new MutableLiveData<>();
        userInfo  = new MutableLiveData<>();
        checkcodeApiServiceService = ApiClient.getCheckcodeClient();
        userApiService = ApiClient.getUserApiServiceClient();
        appApiService = ApiClient.getAppApiServiceClient(getApplication());
    }
    public LiveData<Bitmap> getCaptchaImage() {
        return captchaImage;
    }

    public LiveData<String> getAuthToken() {
        return authToken;
    }

    public LiveData<String> getToastMessage() {
        return toastMessage;
    }

    public LiveData<User> getMyUserInfo() {
        return userInfo;
    }

    //获取验证码图片
    public void getCheckcodeImage() {
        checkcodeApiServiceService.getCheckcodeImage().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        InputStream inputStream = response.body().byteStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        captchaImage.postValue(bitmap);
                    } catch (Exception e) {
                        Log.e("MainViewModel", "Error converting image: " + e.getMessage());
                        toastMessage.postValue("Error loading captcha image");
                    }
                } else {
                    Log.d("MainViewModel", "Failed to get checkcode image: " + response.code());
                    toastMessage.postValue("Failed to get checkcode image");
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("MainViewModel", "Failed to get checkcode image: " + t.getMessage());
                toastMessage.postValue("Failed to get checkcode image");
            }
        });
    }

    //登录获取token
    public void verifyLogin(String account, String password, String verify) {
        userApiService.login(account, password, verify).enqueue(new Callback<Result<String>>() {
            @Override
            public void onResponse(@NonNull Call<Result<String>> call, @NonNull Response<Result<String>> response) {
                if (response.isSuccessful()) {
                    Result<String> result = response.body();
                    if (result != null && result.getCode() == 0) {
                        authToken.postValue(result.getData());
                        try {
                            TokenManager.encryptAndStoreToken(getApplication(), result.getData());
                        } catch (Exception e) {
                            e.printStackTrace();
                            toastMessage.postValue("Error storing token");
                        }
                        toastMessage.postValue("登录成功!");
                    } else {
                        toastMessage.postValue("登录失败: " + result.getMessage());
                    }
                } else {
                    toastMessage.postValue("请求失败: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<Result<String>> call, Throwable t) {
                toastMessage.postValue("请求失败: " + t.getMessage());
            }
        });
    }

    public void getUserInfo() {
        appApiService.getUserInfo().enqueue(new Callback<Result<User>>() {
            @Override
            public void onResponse(Call<Result<User>> call, Response<Result<User>> response) {
                if (response.isSuccessful()) {
                    Result<User> result = response.body();
                    if (result != null && result.getCode() == 0) {
                        User user = result.getData();
                        if(user != null){
                            userInfo.setValue(user);
                        }
                        toastMessage.postValue("用户信息获取成功");
                    } else {
                        toastMessage.postValue("获取用户信息失败: " + result.getMessage());
                    }
                } else {
                    toastMessage.postValue("请求失败: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<Result<User>> call, Throwable t) {
                toastMessage.postValue("网络错误: " + t.getMessage());
            }
        });
    }

}
